const {
  log,
  config,
  utils,
  error,
  Bagua,
  User
} = require('cm')

const actions = {
  async saveBagua (params) {
    const bagua = new Bagua(params.bagua)
    if (params.isFirstSave) {
      await bagua.insert()
    }
    else {
      await bagua.update(params.bagua)
    }
    return bagua.data
  },
  
  async deleteBagua (params) {
    const bagua = new Bagua(params.bagua)
    await bagua.remove()
  },
  
  async getBagua (params) {
    let where = {
      'saveBaguaInfo.author': params.uid,
      title: new RegExp(params.searchKey, 'i')
    }
    if (params.type !== 'all') {
      where.type = params.type
    }
    let collection = Bagua.getCollection('bagua').where(where)
    
    // 排序处理
    let sortKey = 'title'
    if (params.sortType === 'createdTime') {
      sortKey = 'saveBaguaInfo.createdTime'
    }
    else if (params.sortType === 'updatedTime') {
      sortKey = 'saveBaguaInfo.updatedTime'
    }
    collection = collection.orderBy(sortKey, params.sort)
    
    // 获取数量处理
    collection = collection.skip(params.start - 1).limit(params.end - params.start + 1)
    
    const data = await Bagua.doGet(collection, 'bagua')
    return data
  }
}

module.exports = actions